package com.example.assignmentone;

import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends FragmentActivity implements  ActionBar.TabListener {

    /**
     * The serialization (saved instance state) Bundle key representing the
     * current tab position.
     */
    private static final String STATE_SELECTED_NAVIGATION_ITEM = "selected_navigation_item";
    private static final String PREFS_NAME = "TransisionDelayPrefs";
    public static int transitionDelay = 0;
    public static boolean showProgressBetweenTransitions = false;
    public static ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Set up the action bar to show tabs.
        final ActionBar actionBar = getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // For each of the sections in the app, add a tab to the action bar.
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section1).setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section2).setTabListener(this));
        actionBar.addTab(actionBar.newTab().setText(R.string.title_section3).setTabListener(this));
        
        SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
        transitionDelay = settings.getInt("transitionDelay", 0);
        showProgressBetweenTransitions = settings.getBoolean("showProgressBetweenTransitions", false);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Restore the previously serialized current tab position.
        if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
            getActionBar().setSelectedNavigationItem(
                    savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // Serialize the current tab position.
        outState.putInt(STATE_SELECTED_NAVIGATION_ITEM,
                getActionBar().getSelectedNavigationIndex());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
    	SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    	SharedPreferences.Editor editor = settings.edit();
        switch (item.getItemId()) {
            case R.id.delay_increase:
            	transitionDelay += 250;
			    editor.putInt("transitionDelay", transitionDelay);
			    // Commit the edits!
			    editor.commit();
				
				Toast.makeText(getApplicationContext(), "Increased delay with 250ms (" + transitionDelay + ")", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.delay_decrease:
            	transitionDelay -= 250;
			    editor.putInt("transitionDelay", transitionDelay);
			    editor.commit();
				
			    Toast.makeText(getApplicationContext(), "Decreased delay with 250ms (" + transitionDelay + ")", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.delay_reset:
            	transitionDelay = 0;
			    editor.putInt("transitionDelay", transitionDelay);
			    editor.commit();
				
			    Toast.makeText(getApplicationContext(), "Delay has been reset (" + transitionDelay + ")", Toast.LENGTH_SHORT).show();
                return true;
            case R.id.toggle_progress:
            	showProgressBetweenTransitions = !showProgressBetweenTransitions;
            	editor.putBoolean("showProgressBetweenTransitions", showProgressBetweenTransitions);
            	editor.commit();
            	
            	Toast.makeText(getApplicationContext(), "Show progress = " + showProgressBetweenTransitions, Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
    
    @Override
    public void onTabSelected(final ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, show the tab contents in the
        // container view.
    	    	
    	Handler handlerTimer = new Handler();
    	if (showProgressBetweenTransitions)
    		progressDialog = ProgressDialog.show(MainActivity.this, "Loading...", "Please wait...", true, false);
    	
   	 	handlerTimer.postDelayed(new Runnable(){
	   		public void run() {
	   			if (progressDialog != null && progressDialog.isShowing())
	   				progressDialog.dismiss();
	   			Fragment fragment = new DummySectionFragment();
	   	        Bundle args = new Bundle();
	   	        args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, tab.getPosition() + 1);
	   	        fragment.setArguments(args);     
	   	        getSupportFragmentManager().beginTransaction()
	   	                .replace(R.id.container, fragment)
	   	                .commit();       
	   		}
		}, transitionDelay);
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }
        

    /**
     * A dummy fragment representing a section of the app, but that simply
     * displays dummy text.
     */
    public static class DummySectionFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        public static final String ARG_SECTION_NUMBER = "section_number";
        
        public static final String[] transferValues = new String[] {
            "Budget: 0146 1111111111",
            "Salary: 0146 2222222222",
            "Loan:   0146 3333333333"
        };
        
        public static final String[] stockValues = new String[] {
            "Apple:        27,023.50",
            "Microsoft: 15,120.24",
            "Tivoli        11,392.78"
        };

        public DummySectionFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        	        	
        	int currentSection =  getArguments().getInt(ARG_SECTION_NUMBER);
            Log.i("TEST SECTION", "" + currentSection);
        	
        	switch (currentSection) {
			case 1:
				ListView listView1 = new ListView(getActivity());
			    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, transferValues);
			    listView1.setAdapter(adapter1);
	            return listView1;
			case 2:
				ListView listView2 = new ListView(getActivity());
			    ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(inflater.getContext(), android.R.layout.simple_list_item_1, stockValues);
			    listView2.setAdapter(adapter2);
	            return listView2;
			case 3:
				View myFragmentView = inflater.inflate(R.layout.account_linear, container, false);
				Button transferButton = (Button) myFragmentView.findViewById(R.id.button1);
				transferButton.setOnClickListener(new View.OnClickListener() {
		             public void onClick(View v) {
		            	 Handler handlerTimer = new Handler();
		            	 if (showProgressBetweenTransitions)
		            		 progressDialog = ProgressDialog.show(getActivity(), "Transfering money...", "Please wait...", true, false);
		            	 handlerTimer.postDelayed(new Runnable(){
		            		 public void run() {
		            			 if (progressDialog != null && progressDialog.isShowing())
		            				 progressDialog.dismiss();
		            			 Toast.makeText(getActivity(), "Money transfered", Toast.LENGTH_SHORT).show();             
		            		 }
	            		 }, transitionDelay);
		             }
		         });
				
				return myFragmentView;

			default:
				break;
			}

            return null;
            
        }
    }    
}
